# 文件名称：fix_mysql_service.ps1
# 功能说明：一键修复MySQL服务问题

param(
    [switch]$Force,  # 强制执行所有修复步骤
    [string]$ServiceName = "MySQL80"
)

# 检查管理员权限
function Test-AdminRights {
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

Write-Host "🔧 MySQL服务修复工具" -ForegroundColor Cyan
Write-Host "=====================" -ForegroundColor Cyan

# 检查管理员权限
if (-not (Test-AdminRights)) {
    Write-Host "❌ 此脚本需要管理员权限才能修复MySQL服务问题" -ForegroundColor Red
    Write-Host "请右键点击PowerShell，选择'以管理员身份运行'，然后重新执行此脚本" -ForegroundColor Yellow
    Write-Host "" -ForegroundColor Gray
    Write-Host "或者复制以下命令到管理员PowerShell中执行:" -ForegroundColor Yellow
    Write-Host "cd '$PWD'; .\fix_mysql_service.ps1" -ForegroundColor White
    exit 1
}

Write-Host "👑 已确认管理员权限" -ForegroundColor Green

try {
    # 步骤1：检查MySQL服务状态
    Write-Host "" -ForegroundColor Gray
    Write-Host "📊 步骤1：检查MySQL服务状态" -ForegroundColor Yellow
    $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
    
    if (-not $service) {
        Write-Host "❌ 未找到MySQL服务: $ServiceName" -ForegroundColor Red
        Write-Host "请确认MySQL已正确安装" -ForegroundColor Yellow
        exit 1
    }
    
    $serviceInfo = Get-CimInstance -ClassName Win32_Service -Filter "Name='$ServiceName'"
    Write-Host "   服务状态: $($service.Status)" -ForegroundColor White
    Write-Host "   启动类型: $($serviceInfo.StartMode)" -ForegroundColor White
    Write-Host "   服务账户: $($serviceInfo.StartName)" -ForegroundColor White
    
    # 步骤2：配置服务为自动启动
    Write-Host "" -ForegroundColor Gray
    Write-Host "🔧 步骤2：配置服务自动启动" -ForegroundColor Yellow
    
    if ($serviceInfo.StartMode -ne "Auto" -or $Force) {
        Write-Host "   正在设置MySQL服务为自动启动..." -ForegroundColor White
        Set-Service -Name $ServiceName -StartupType Automatic
        Write-Host "   ✅ 已设置为自动启动" -ForegroundColor Green
    } else {
        Write-Host "   ✅ 服务已配置为自动启动" -ForegroundColor Green
    }
    
    # 步骤3：配置故障恢复
    Write-Host "" -ForegroundColor Gray
    Write-Host "🛡 步骤3：配置故障自动恢复" -ForegroundColor Yellow
    
    Write-Host "   正在配置服务失败时自动重启..." -ForegroundColor White
    $result = sc.exe failure $ServiceName reset= 86400 actions= restart/60000/restart/60000/restart/60000
    if ($LASTEXITCODE -eq 0) {
        Write-Host "   ✅ 故障恢复配置完成" -ForegroundColor Green
    } else {
        Write-Host "   ⚠ 故障恢复配置可能失败" -ForegroundColor Yellow
    }
    
    # 步骤4：设置服务描述
    Write-Host "" -ForegroundColor Gray
    Write-Host "📝 步骤4：更新服务描述" -ForegroundColor Yellow
    
    $description = "MySQL Database Server - Auto-configured for DEV_VISION project"
    sc.exe description $ServiceName $description | Out-Null
    Write-Host "   ✅ 服务描述已更新" -ForegroundColor Green
    
    # 步骤5：启动服务
    Write-Host "" -ForegroundColor Gray
    Write-Host "🚀 步骤5：启动MySQL服务" -ForegroundColor Yellow
    
    if ($service.Status -ne 'Running') {
        Write-Host "   正在启动MySQL服务..." -ForegroundColor White
        Start-Service -Name $ServiceName
        Start-Sleep -Seconds 3
        
        $service.Refresh()
        if ($service.Status -eq 'Running') {
            Write-Host "   ✅ MySQL服务启动成功" -ForegroundColor Green
        } else {
            Write-Host "   ❌ MySQL服务启动失败，状态: $($service.Status)" -ForegroundColor Red
        }
    } else {
        Write-Host "   ✅ MySQL服务已在运行" -ForegroundColor Green
    }
    
    # 步骤6：创建监控脚本
    Write-Host "" -ForegroundColor Gray
    Write-Host "🔍 步骤6：创建监控守护脚本" -ForegroundColor Yellow
    
    $scriptsDir = "E:\DEV_VISION\scripts"
    if (-not (Test-Path $scriptsDir)) {
        New-Item -ItemType Directory -Path $scriptsDir -Force | Out-Null
    }
    
    $watchdogScript = @"
# MySQL服务监控守护脚本
# 每30秒检查MySQL服务，如果停止则自动重启

`$serviceName = "$ServiceName"
`$logDir = "E:\DEV_VISION\logs"
`$logFile = "`$logDir\mysql_watchdog.log"

# 创建日志目录
if (-not (Test-Path `$logDir)) {
    New-Item -ItemType Directory -Path `$logDir -Force | Out-Null
}

function Write-Log {
    param([string]`$Message)
    `$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    `$logEntry = "[$timestamp] `$Message"
    Write-Host `$logEntry -ForegroundColor Cyan
    Add-Content -Path `$logFile -Value `$logEntry
}

function Test-AdminRights {
    `$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    `$principal = New-Object Security.Principal.WindowsPrincipal(`$currentUser)
    return `$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

Write-Log "MySQL监控守护进程启动"

if (-not (Test-AdminRights)) {
    Write-Log "警告: 运行在非管理员权限下，可能无法重启服务"
}

while (`$true) {
    try {
        `$service = Get-Service -Name `$serviceName -ErrorAction SilentlyContinue
        
        if (-not `$service) {
            Write-Log "错误: 未找到MySQL服务 `$serviceName"
            Start-Sleep -Seconds 60
            continue
        }
        
        if (`$service.Status -ne 'Running') {
            Write-Log "检测到MySQL服务已停止 (状态: `$(`$service.Status))，尝试重启..."
            
            if (Test-AdminRights) {
                try {
                    Start-Service -Name `$serviceName -ErrorAction Stop
                    Start-Sleep -Seconds 3
                    `$service.Refresh()
                    
                    if (`$service.Status -eq 'Running') {
                        Write-Log "✅ MySQL服务重启成功"
                    } else {
                        Write-Log "❌ MySQL服务重启失败，当前状态: `$(`$service.Status)"
                    }
                } catch {
                    Write-Log "❌ 重启MySQL服务时发生错误: `$(`$_.Exception.Message)"
                }
            } else {
                Write-Log "❌ 缺少管理员权限，无法重启服务"
            }
        }
    } catch {
        Write-Log "监控过程中发生错误: `$(`$_.Exception.Message)"
    }
    
    Start-Sleep -Seconds 30
}
"@
    
    $watchdogPath = "$scriptsDir\mysql_watchdog.ps1"
    Set-Content -Path $watchdogPath -Value $watchdogScript -Encoding UTF8
    Write-Host "   ✅ 监控脚本已创建: $watchdogPath" -ForegroundColor Green
    
    # 步骤7：创建快速启动批处理文件
    Write-Host "" -ForegroundColor Gray
    Write-Host "⚡ 步骤7：创建快速启动脚本" -ForegroundColor Yellow
    
    $quickStartBat = @"
@echo off
title MySQL Quick Start
echo 🚀 快速启动MySQL服务...
net start $ServiceName
if %ERRORLEVEL% == 0 (
    echo ✅ MySQL服务启动成功
) else (
    echo ❌ MySQL服务启动失败
    echo 💡 请尝试以管理员身份运行
)
pause
"@
    
    $quickStartPath = "E:\DEV_VISION\quick_start_mysql.bat"
    Set-Content -Path $quickStartPath -Value $quickStartBat -Encoding ASCII
    Write-Host "   ✅ 快速启动脚本已创建: $quickStartPath" -ForegroundColor Green
    
    # 完成总结
    Write-Host "" -ForegroundColor Gray
    Write-Host "🎉 MySQL服务修复完成！" -ForegroundColor Green
    Write-Host "========================" -ForegroundColor Green
    Write-Host "" -ForegroundColor Gray
    Write-Host "✅ 已完成的配置:" -ForegroundColor White
    Write-Host "   • MySQL服务设置为自动启动" -ForegroundColor White
    Write-Host "   • 配置了故障自动恢复" -ForegroundColor White
    Write-Host "   • 创建了监控守护脚本" -ForegroundColor White
    Write-Host "   • 创建了快速启动脚本" -ForegroundColor White
    Write-Host "" -ForegroundColor Gray
    Write-Host "💡 可选的额外保护措施:" -ForegroundColor Yellow
    Write-Host "   1. 启动监控守护进程:" -ForegroundColor White
    Write-Host "      powershell -ExecutionPolicy Bypass -File `"$watchdogPath`"" -ForegroundColor Cyan
    Write-Host "" -ForegroundColor Gray
    Write-Host "   2. 使用快速启动脚本:" -ForegroundColor White
    Write-Host "      双击 quick_start_mysql.bat" -ForegroundColor Cyan
    Write-Host "" -ForegroundColor Gray
    Write-Host "   3. 使用增强版启动脚本:" -ForegroundColor White
    Write-Host "      .\run_enhanced.ps1" -ForegroundColor Cyan
    
} catch {
    Write-Host "❌ 修复过程中发生错误: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}
